import { computed, reactive, ref } from "vue";
import { getListApi as channelApi } from "@/api/configCenter/outBoundAgent";
import { getListApi as countryApi } from "@/api/configCenter/countryRegion";

export default function InitHook() {
  //表单数据
  const formState = reactive<InsuranceCompany.editForm>({
    name: "", //	保险公司名称
    agentIdList: [], //	出仓代理集合
    goodLimitResList: [
      {
        countryId: "",
        goodValueLimit: 0,
        channelIdList: [],
        goodLimitUnit: ""
      }
    ],
    id: ""
  });

  const channelOpts = ref<any>([]); //出仓代理
  const countryOpts = ref<any>([]); //国家
  const tableData = reactive([]); //表格数据
  const loading = ref<boolean>(false); //等待状态

  //获取渠道
  const getChannelApi = () => {
    return channelApi({ pageNum: 1, pageSize: 9999, total: 9, status: 1, name: "", beforePageNum: 1 }).then((res: any) => {
      const { records } = res.data;
      channelOpts.value = records.map((t: any) => {
        return { name: t.name, id: t.id };
      });
    });
  };
  //获取国家
  const getCountryApi = () => {
    return countryApi({ pageNum: 1, pageSize: 9999, total: 9, status: 1, beforePageNum: 1 }).then((res: any) => {
      const { records } = res.data;
      countryOpts.value = records.map((t: any) => {
        return { name: t.region, id: t.id };
      });
    });
  };

  //存储选取的数组
  const selectValue = computed(() => {
    const valueMap = new Map<string, string[]>();

    for (let i = 0; i < formState.goodLimitResList.length; i++) {
      const target = formState.goodLimitResList[i];
      let result: Array<string> = [];
      if ([...valueMap.keys()].includes(target.countryId)) {
        result = (valueMap.get(target.countryId) as string[]).concat(target.channelIdList.map((t: any) => t[t.length - 1]));
      } else {
        result = target.channelIdList.map((t: any) => t[t.length - 1]);
      }

      valueMap.set(target.countryId, result);
    }

    return valueMap;
  });
  //表单ref
  const formRef = ref(null);
  return {
    tableData,
    formState,
    loading,
    formRef,
    getChannelApi,
    channelOpts,
    getCountryApi,
    countryOpts,
    selectValue
  };
}
